﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shop.Model;
using System.Web;
using Shop.Framework.Keys;
using System.Web.Caching;
using System.Web.Script.Serialization;


namespace Shop.Framework.Services {
    public class CategoryService:BaseService {

        public List<Category> GetCategories() {
            ShopDatabaseDataContext context = Context;
            List<Category> categories = HttpRuntime.Cache.Get(CacheKey.CategoryList) as List<Category>;
            
            if (categories == null) {
                categories = context.Categories.ToList();
                HttpRuntime.Cache.Add(CacheKey.CategoryList,
                    categories,
                    null,
                    DateTime.Now.AddHours(2),
                    Cache.NoSlidingExpiration,
                    CacheItemPriority.Normal,
                    null);
            }            

            return categories;
        }

        public void Save(List<Category> categorlist) {
            ShopDatabaseDataContext context = Context;            
        }


        public Category GetCategoryById(int idCategory) {
            Category cat = GetCategories().FirstOrDefault(c => c.IdCategory == idCategory);
            return cat;
        }

        internal string GetCategoriesJson() {
            Random rand = new Random();
            List<Category> catList = GetCategories();

            List<TagTemplate> tList = new List<TagTemplate>();
            foreach (var t in catList) {

                tList.Add(new TagTemplate { 
                    tag = t.Name, 
                    freq = RandomNumber(rand).ToString(), 
                    link = string.Format("/{0}-{1}.html",t.Name.Trim(), t.IdCategory) 
                    });             
            }

            JavaScriptSerializer ser = new JavaScriptSerializer();
            //StringBuilder builder = new StringBuilder();
            return ser.Serialize(tList);
        }

        private int RandomNumber(Random rand) {            
            return rand.Next(1,20);
        }

        private class TagTemplate {
            public string tag { get; set; }
            public string freq { get; set; }
            public string link { get; set; }
        }
    }
}
 